package cn.niit.pm.controller;


import cn.niit.pm.entity.Employee;
import cn.niit.pm.service.EmployeeService;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
 * fahui
 * 岗位信息的Controller
 * */
@Slf4j
@Api(value = "测试接口", tags = "员工管理相关的接口")
@RequestMapping("/employee_infor")
@Controller
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService; //用于调用service接口
    /*
     * (点击左侧栏目后的请求——最后渲染员工信息页面)
     * */
    @GetMapping("/employee_infor")
    public String staffinfoIndex(Model model, Employee employee){
        System.out.println("===========employee_infor==============");
        List<Employee> employeeList = employeeService.selectListByEmployee(employee);
        System.out.println("employeeList:"+employeeList);
        /** 构造分页对象 */
        PageInfo<Employee> page = new PageInfo<Employee>(employeeList);
        log.info("分页结果对象PageInfor:{}", page);
        model.addAttribute("employeeList",employeeList);
        model.addAttribute("pageInfo", page);
        return "employee_infor/employee_infor";
    }
    //////////////////
    ///////添加////////
    /*
     * 点击“添加或修改”按钮 发送get请求——跳转到员工添加或修改页面(并且初始化页面)
     * */
    @GetMapping("/{id}")
    public  String intoAdd(Model model, @PathVariable("id") Long employeeId){
        Employee employee = null;
        if (null != employeeId && employeeId > 0){
            employee = employeeService.selectByEmployeeId(employeeId);
        }else {
            employee = new Employee();
        }
        model.addAttribute("employee",employee);
        return "employee_infor/add_employee";
    }
    /*
     * 添加内容填写完毕后 点击“保存”发送post请求
     * */
    @PostMapping("")
    public String addEmployee(Model model, @Validated Employee employee, BindingResult result, HttpServletRequest request){
        log.info("待添加的用户信息：{}", employee);
        if(result.hasErrors()){
            Map<String, String> errMap = new HashMap<>();
            for(FieldError error : result.getFieldErrors()){
                log.warn("参数校验异常：{} ，提示信息： {} ", error.getField(), error.getDefaultMessage());
                errMap.put(error.getField(), error.getDefaultMessage());
            }
            model.addAttribute("errors", errMap);
            model.addAttribute("employee", employee);
            return "employee_infor/add_employee";
        }
        Employee loginEmployee = (Employee) request.getSession().getAttribute("employee");
        employee.setCreateUserId(loginEmployee.getEmployeeId());
        employee.setCreateUserName(loginEmployee.getEmployeeName());
        employee.setGmtCreate(new Date());
        int rows = employeeService.insertEmployee(employee);
        return "redirect:/employee_infor/employee_infor";
    }


    /**
     * 更新内容完毕后，点击“保存”按钮，发送put请求
     */
    @PutMapping("")
    public String updateEmployee(Employee employee, HttpServletRequest request){
        Employee loginEmployee = (Employee) request.getSession().getAttribute("employee");
        log.info("待更新的用户：{}", employee);
        //为修改的记录赋值更新人信息
        employee.setModifyUserId(loginEmployee.getEmployeeId());
        employee.setModifyUserName(loginEmployee.getEmployeeName());
        employee.setGmtModified(new Date());
        int rows = employeeService.updateEmployee(employee);
        log.info("被更新的记录数：{}", rows);
        if(rows <= 0){
            return "/add_employee";
        }
        return "redirect:/employee_infor/employee_infor";
    }


    /**
     * 删除用户
     * @param employeeId
     * @return
     */
    @ResponseBody
    @DeleteMapping("/{id}")
    public String deletEmployee(@PathVariable("id") Long employeeId){
        System.out.println(employeeId);
        int rows = 0;
        if(null != employeeId){
            rows = employeeService.deleteByEmployeeId(employeeId);
            if(rows > 0){
                return "true";
            }
        }
        return "false";
    }
}
